import React, { useEffect } from 'react';
import { Card, Typography, Form, Input, Button, Switch, message as globalMessage, Select, ColorPicker, App } from 'antd';
import type { FormInstance } from 'antd';
import { SaveOutlined } from '@ant-design/icons';
import NumberField from '../../components/common/NumberField';
import { useTheme } from '../../components/ThemeProvider';
import { THEME_COLOR_OPTIONS, formatColorToHex } from '../../utils/themeUtils';
import ThemeSwitcher from '../../components/common/ThemeSwitcher';

// 定义表单数据类型
interface SettingsFormValues {
  enableHistory: boolean;
  autoSaveReports: boolean;
  defaultExportFormat: string;
  themeColor: string;
  themeType: string;
  useCompactTheme: boolean; // 添加紧凑主题选项
  historyMaxCount: number;
}

// 主题类型选项常量
const THEME_TYPE_OPTIONS = [
  { label: '亮色', value: 'light' },
  { label: '暗色', value: 'dark' },
];

const { Title } = Typography;

const SettingsPage: React.FC = () => {
  const [form]: [FormInstance<SettingsFormValues>] = Form.useForm<SettingsFormValues>();
  const { themeSettings, updateThemeColor, toggleThemeType, toggleCompactMode } = useTheme();
  const presetSwatches = THEME_COLOR_OPTIONS.map(o => o.value);

  // 从localStorage加载设置
  useEffect(() => {
    try {
      const savedSettings = localStorage.getItem('appSettings');
      if (savedSettings) {
        const settings = JSON.parse(savedSettings);
        // 确保useCompactTheme字段与themeSettings保持同步
        const loadedSettings = {
          ...settings,
          // 优先使用useCompactTheme，如果不存在则使用useCompact的值
          useCompactTheme: settings.useCompactTheme !== undefined ? settings.useCompactTheme : settings.useCompact
        };
        form.setFieldsValue(loadedSettings);
      } else {
        // 如果没有保存的设置，使用themeSettings中的值初始化表单
        form.setFieldsValue({
          themeColor: themeSettings.colorPrimary,
          themeType: themeSettings.themeType,
          useCompactTheme: themeSettings.useCompact
        });
      }
    } catch (error) {
      console.error('Failed to load settings:', error);
      // 发生错误时，使用当前themeSettings的值
      form.setFieldsValue({
        themeColor: themeSettings.colorPrimary,
        themeType: themeSettings.themeType,
        useCompactTheme: themeSettings.useCompact
      });
    }
  }, [form, themeSettings]);

  const onFinish = (values: SettingsFormValues) => {
    try {
      // 保存设置到localStorage
      localStorage.setItem('appSettings', JSON.stringify(values));
      
      // 使用主题Hook更新主题设置
      updateThemeColor(values.themeColor);
      toggleThemeType(values.themeType as 'light' | 'dark');
      toggleCompactMode(values.useCompactTheme);
      
      // 通知成功
      globalMessage.success('设置已保存');
    } catch (error) {
      globalMessage.error('保存设置失败');
      console.error('Failed to save settings:', error);
    }
  };

  // 当颜色更改时，立即保存并应用
  const handleColorChange = (color: any) => {
    try {
      const colorString = formatColorToHex(color);
      form.setFieldValue('themeColor', colorString);
      
      // 直接使用主题Hook更新颜色，但让onFinish处理保存到localStorage
      updateThemeColor(colorString);
    } catch (e) {
      console.error('handleColorChange failed', e);
    }
  };

  // 当主题类型更改时，立即应用
  const handleThemeTypeChange = (themeType: string) => {
    try {
      form.setFieldValue('themeType', themeType);
      
      // 直接使用主题Hook切换主题类型，但让onFinish处理保存到localStorage
      toggleThemeType(themeType as 'light' | 'dark');
    } catch (e) {
      console.error('handleThemeTypeChange failed', e);
    }
  };
  
  // 当紧凑模式设置更改时，立即应用
  const handleCompactThemeChange = (useCompactTheme: boolean) => {
    try {
      form.setFieldValue('useCompactTheme', useCompactTheme);
      
      // 直接使用主题Hook切换紧凑模式
      toggleCompactMode(useCompactTheme);
      
      // 立即保存设置到localStorage，确保页面切换后设置正确
      const currentValues = form.getFieldsValue();
      const updatedValues = {
        ...currentValues,
        useCompactTheme: useCompactTheme,
        useCompact: useCompactTheme // 同时更新两个字段以保持兼容性
      };
      localStorage.setItem('appSettings', JSON.stringify(updatedValues));
      
      // 不再在这里显示保存成功提示，避免与onValuesChange中的提示重复
      // globalMessage.success('设置已保存', 1);
    } catch (e) {
      console.error('handleCompactThemeChange failed', e);
      globalMessage.error('保存设置失败');
    }
  };

  return (
    <div className="settings-page">
      <div className="settings-header">
        <Title level={2} className="app-title">设置</Title>
        <ThemeSwitcher />
      </div>
      
      <Card title="常规设置" className="settings-card">
        <Form
          form={form}
          layout="vertical"
          onFinish={onFinish}
          initialValues={{
            enableHistory: true,
            autoSaveReports: true,
            defaultExportFormat: 'docx',
            themeColor: '#1890ff',
            themeType: 'light',
            useCompactTheme: false, // 默认为非紧凑模式
            historyMaxCount: 20
          }}
          onValuesChange={(changedValues, allValues) => {
            try {
              // 当任何表单值变化时自动保存
              localStorage.setItem('appSettings', JSON.stringify(allValues));
              
              // 如果修改了历史记录个数设置，触发自定义事件通知其他页面
              if (changedValues.historyMaxCount !== undefined) {
                window.dispatchEvent(new CustomEvent('app-settings-changed', {
                  detail: { historyMaxCount: changedValues.historyMaxCount }
                }));
              }
              
              // 显示保存成功提示
              globalMessage.success('设置已自动保存', 1); // 1秒后自动关闭
            } catch (error) {
              console.error('Failed to auto-save settings:', error);
            }
          }}
        >
          <Form.Item 
            name="enableHistory" 
            label="启用计算历史记录" 
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>
          
          <NumberField 
            name="historyMaxCount" 
            label={
              <span>
                计算历史记录保存个数
                <div style={{ fontSize: '12px', color: 'var(--app-text-secondary, #666)', fontWeight: 'normal', marginTop: '2px' }}>
                  设置最多保存的计算历史记录数量
                </div>
              </span>
            }
            min={1}
            max={100}
            step={1}
            message="请输入有效的历史记录保存个数（1-100）"
          />
          
          <Form.Item 
            name="autoSaveReports" 
            label="自动保存计算报告" 
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>
          
          <Form.Item 
            name="defaultExportFormat" 
            label="默认导出格式"
          >
            <Input placeholder="默认导出格式" />
          </Form.Item>
        </Form>
      </Card>
      
      <Card title="外观设置" className="settings-card">
        <Form
          form={form}
          layout="vertical"
          onValuesChange={(changedValues, allValues) => {
            try {
              // 当任何表单值变化时自动保存
              localStorage.setItem('appSettings', JSON.stringify(allValues));
              
              // 显示保存成功提示
              globalMessage.success('设置已自动保存', 1); // 1秒后自动关闭
            } catch (error) {
              console.error('Failed to auto-save settings:', error);
            }
          }}
          onFinish={onFinish}
        >
          <Form.Item 
            name="themeColor" 
            label={
              <span>
                主题颜色
                <div className="app-text-tertiary" style={{ fontSize: '12px', fontWeight: 'normal', marginTop: '2px' }}>
                  选择应用的主题颜色
                </div>
              </span>
            }>
            <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--ant-space-md)' }}>
              <ColorPicker
                value={themeSettings.colorPrimary}
                onChange={handleColorChange}
                className="theme-color-picker"
              />
              <div style={{ width: 24, height: 24, borderRadius: 'var(--ant-radius-sm)', background: themeSettings.colorPrimary, border: '1px solid var(--ant-color-border)' }} />
              <div style={{ display: 'flex', gap: 'var(--ant-space-xs)', marginLeft: 'var(--ant-space-sm)' }}>
                {presetSwatches.map((s) => (
                  <div key={s} onClick={() => handleColorChange(s)} style={{ width: 20, height: 20, borderRadius: 'var(--ant-radius-sm)', background: s, cursor: 'pointer', border: '1px solid var(--ant-color-border)', transition: 'border-color var(--ant-transition-fast)' }} />
                ))}
              </div>
            </div>
          </Form.Item>
          
          <Form.Item 
            name="themeType" 
            label={
              <span>
                主题类型
                <div className="app-text-tertiary" style={{ fontSize: '12px', fontWeight: 'normal', marginTop: '2px' }}>
                  选择亮色或暗色主题
                </div>
              </span>
            }>
            <Select 
              options={THEME_TYPE_OPTIONS} 
              style={{ width: 200 }}
              placeholder="选择主题类型"
              onChange={handleThemeTypeChange}
              className="theme-type-select"
            />
          </Form.Item>
          
          <Form.Item 
            name="useCompactTheme" 
            label="使用紧凑模式" 
            help="紧凑模式可以减少界面元素之间的间距，适合小屏幕显示"
            valuePropName="checked"
          >
            <Switch onChange={handleCompactThemeChange} />
          </Form.Item>
          
        </Form>
      </Card>
      
      <Card title="计算历史记录" className="settings-card">
        <p>计算历史记录已移至单独的页面。</p>
        <p>您可以在侧边栏的"计算历史"菜单项中查看和管理所有计算记录。</p>
      </Card>
    </div>
  );
};

export default SettingsPage;